package com.kxxnzstdsw.plugins

import com.auth0.jwk.JwkProvider
import com.kxxnzstdsw.exception.can.AuthenticationException
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.response.*
import kotlinx.serialization.Serializable
import org.koin.ktor.ext.inject

@Serializable
data class User(
  val username: String,
  val accountId: String
// TODO: 需要什么往里头放什么
) : Principal

fun Application.configureSecurity() {
//  val e by inject<Enforcer>()
  val jwkProvider by inject<JwkProvider>()
  install(Authentication) {
    jwt {
      verifier(jwkProvider) {
        acceptLeeway(3)
      }

      validate { credential ->
//        casbin  获取请求的api 获取用户信息 获取动作 判断是否有权限
//        if (e.enforce(this.user().accountId, this.request.path(), this.request.httpMethod.value)) {
          JWTPrincipal(credential.payload)
//        } else {
//          throw UnauthorizedException()
//        }
      }
      challenge { defaultScheme, realm ->
        call.respond(HttpStatusCode.Unauthorized, "Token is not valid or has expired")
      }
    }
  }
}

fun ApplicationCall.user() =
  authentication.principal<User>() ?: throw AuthenticationException()

